/* eslint-disable no-undef */
export function MapLoader() {
  return new Promise((resolve, reject) => {
    if (window.AMap) {
      resolve(window.AMap)
    } else {
      // 动态创建script标签
      var script = document.createElement('script')
      script.type = 'text/javascript'
      script.async = true
      script.src =
        'https://webapi.amap.com/maps?v=2.0&callback=initAMap&key=b1df89d3d2693cf20eb7c5e6c52d0ce5'
      script.onerror = reject
      document.head.appendChild(script)
    }
    window.initAMap = () => {
      resolve(window.AMap)
    }
  })
}
var infoWin
var tableDom
/**
 * 封装便捷的撞题
 * @param {AMap.Map} map
 * @param {Array} event
 * @param {Object} content
 */
export function openInfoWin(map, event, content) {
  if (!infoWin) {
    infoWin = new AMap.InfoWindow({
      autoMove: false,
      isCustom: true, // 使用自定义窗体
      offset: new AMap.Pixel(130, 100),
    })
  }

  var x = event.offsetX
  var y = event.offsetY
  var lngLat = map.containerToLngLat(new AMap.Pixel(x, y))

  if (!tableDom) {
    const infoDom = document.createElement('div')
    infoDom.className = 'info'
    infoDom.style =
      'background: #FFFFFF; color: #A0A7B4; padding: 10px; max-width: 300px;  min-width: 200px; font-size: 12px;'
    tableDom = document.createElement('table')
    infoDom.appendChild(tableDom)
    infoWin.setContent(infoDom)
  }

  var trStr = ''
  for (var name in content) {
    var val = content[name]
    trStr +=
      '<tr>' +
      '<td class="label">' +
      name +
      '</td>' +
      '<td>&nbsp;</td>' +
      '<td class="content">' +
      val +
      '</td>' +
      '</tr>'
  }

  tableDom.innerHTML = trStr
  tableDom.style = ' text-align: center;color: grey;max-width: 200px;'
  infoWin.open(map, lngLat)
}

export function closeInfoWin() {
  if (infoWin) {
    infoWin.close()
  }
}
